/**
 * 产品运作周报
 * @author tongsitong
 */

import { BorderRedBtn } from "@/components/Button";
import ColumnSelector from "@/components/ColumnSelectorFilter";
import { RedDownArrow,DownImage } from "@/components/Icon";
import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import LittleTitle from "@/components/Title/littleTitle";
import icon_setting from "@/assets/icons/icon-set.png";
import { Button, Popover, Spin, Table } from "antd";
import { RidingHeader, NewText } from "../RidingReturns";
import CusDatePicker from "@/components/Picker/datePicker";
import { FlexDiv } from "@/components/FOF/DoubleInput";
import { InfoTable } from "./component/InfoTable";
import SSelect from "@/components/Select";
import { Select } from "antd";
import dayjs from 'dayjs';

import { exportExcel, getUrlParam, Export_Img_Tool } from "@/utils/utils";


import {
  getReportRate,
  queryFundBasicInfoList,
  export_portfolio_rep_info,
  get_last_job_time,
} from "./service";

import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import styles from "./index.less";
import TableChart from "./component/tableChart";
import ReportLine from "./component/Line";

import icon_logo from "@/assets/icons/icon_logo.png";

let PDF = getUrlParam("type") === "img";

const selectList = [
  {
    key: "1",
    value: "周",
  },
  {
    key: "2",
    value: "月",
  },
  {
    key: "3",
    value: "自定义",
  },
];


const treeResult = {
  res: [
    {
      id: "加权利率",
      title: "加权利率（%）",
      pid: null,
      name: null,
      children: [
        {
          id: "rate",
          // pid: "加权利率",
          title: "合计",
          checked: true,
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR001",
          title: "R001",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR007",
          title: "R007",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR014",
          title: "R014",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR021",
          title: "R021",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR1M",
          title: "R1M",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR2M",
          title: "R2M",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR3M",
          title: "R3M",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR4M",
          title: "R4M",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR5M",
          title: "R5M",
          parentKeys: ["加权利率"],
        },
        {
          id: "rateR6M",
          title: "R6M",
          parentKeys: ["加权利率"],
        },
      ],
    },
    {
      id: "回购笔数（笔）",
      title: "回购笔数（笔）",
      pid: null,
      name: null,
      children: [
        {
          id: "count",
          title: "合计",
          checked: true,
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR001",
          title: "R001",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR007",
          title: "R007",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR014",
          title: "R014",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR021",
          title: "R021",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR1M",
          title: "R1M",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR2M",
          title: "R2M",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR3M",
          title: "R3M",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR4M",
          title: "R4M",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR5M",
          title: "R5M",
          parentKeys: ["回购笔数（笔）"],
        },
        {
          id: "countR6M",
          title: "R6M",
          parentKeys: ["回购笔数（笔）"],
        },
      ],
    },
    {
      id: "回购金额（亿）",
      title: "回购金额（亿）",
      pid: null,
      name: null,
      children: [
        {
          id: "sumNetCapital",
          title: "合计",
          checked: true,
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR001",
          title: "R001",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR007",
          title: "R007",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR014",
          title: "R014",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR021",
          title: "R021",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR1M",
          title: "R1M",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR2M",
          title: "R2M",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR3M",
          title: "R3M",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR4M",
          title: "R4M",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR5M",
          title: "R5M",
          parentKeys: ["回购金额（亿）"],
        },
        {
          id: "sumNetCapitalR6M",
          title: "R6M",
          parentKeys: ["回购金额（亿）"],
        },
      ],
    },
    {
      id: "金额占比（%）",
      title: "金额占比（%）",
      pid: null,
      name: null,
      children: [
        {
          id: "moneyRatio",
          title: "合计",
          checked: true,
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR001",
          title: "R001",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR007",
          title: "R007",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR014",
          title: "R014",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR021",
          title: "R021",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR1M",
          title: "R1M",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR2M",
          title: "R2M",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR3M",
          title: "R3M",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR4M",
          title: "R4M",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR5M",
          title: "R5M",
          parentKeys: ["金额占比（%）"],
        },
        {
          id: "moneyRatioR6M",
          title: "R6M",
          parentKeys: ["金额占比（%）"],
        },
      ],
    },
  ],
};

const handleTreeData = (treeData) => {
  treeData.map((item) => {
    item.key = item.id;
    item.type = item.id;
    if (item.children) {
      handleTreeData(item.children);
    }
  });
};

handleTreeData(treeResult.res);

console.log(treeResult);
const DEFAULT_CHECKEDKEYS = ["rate", "count", "sumNetCapital", "moneyRatio"]; // 固定选中的列

export function ProductReport() {
  const [columnSetVisible, setColumnSetVisible] = useState(false); // 列选择器
  const [searchTableFieldDTOList, setSearchTableFieldDTOList] = useState([]); //树选择结构
  const [checkedKeys, setCheckedKeys] = useState(DEFAULT_CHECKEDKEYS); // 列选择器
  const [confirmCheckedKeys, setConfirmCheckedKeys] =
    useState(DEFAULT_CHECKEDKEYS);
  const [checkedIds, setCheckedIds] = useState([]); // 列选择器
  const [start, setStart] = useState<any>(getUrlParam("start"));
  const [end, setEnd] = useState<any>(getUrlParam("end"));
  const [type, setType] = useState(getUrlParam("checkType") || "1");
  const [systemTime, setSystemTime] = useState<number>(Date.now());
  const [innerCode, setInnerCode] = useState(getUrlParam("innerCode"));
  const [fundName, setFundName] = useState(
    getUrlParam("fundName")
      ? decodeURI(getUrlParam("fundName"))
      : "东海鑫享66个月定开"
  ); //固定写死
  const [fundList, setFundList] = useState([]);
  const [isReportRateReady, setIsReportRateReady] = useState(false); //折线图接口是否调完
  const [reportLineData, setReportLineData] = useState({}); //折线图数据
  const [updateTime, setUpdateTime] = useState(undefined);
  const [canDownLoadPdf, setCanDownLoadPdf] = useState(false);
  const [tableInfoReady, setTableInfoReady] = useState(false);
  const [tableChartInfoReady, setTableChartInfoReady] = useState(false);

  const [tableList, setTableList] = useState({}); // 回购信息

  useEffect(() => {
    //如果所有的数据都已经请求完毕
    if (isReportRateReady && tableInfoReady && tableChartInfoReady) {
      setCanDownLoadPdf(true);
    }
  }, [isReportRateReady, tableInfoReady, tableChartInfoReady]);

  const onClickExportData = () => {
    handleExportData(
      {
        innerCode,
        start: dayjs(start).format("YYYY-MM-DD"),
        end: dayjs(end).format("YYYY-MM-DD"),
        fieldList: confirmCheckedKeys.map((item) => ({
          key: item,
        })),
      },
      `${fundName}运作${type == "1" ? "周" : type == "2" ? "月" : ""}报${
        type == "3" ? "表" : ""
      } ( ${dayjs(start).format("YYYY-MM-DD")} ~ ${dayjs(end).format(
        "YYYY-MM-DD"
      )} )`
    );
  };

  // 导出数据
  const handleExportData = async (params: any, title: string) => {
    const response: Blob = await export_portfolio_rep_info(params);
    exportExcel(response, title, true);
  };

  // 改变自定义列
  const changeColumns = (arr: any[]) => {
    // 点击确认后选择的列
    setConfirmCheckedKeys(checkedKeys);
    setColumnSetVisible(false);
  };

  const changeCheckedKeys = (checkedArr: any) => {
    console.log("changeCheckedKeys", checkedArr);
    setCheckedKeys(checkedArr); //展示用
  };

  const changeCheckedIds = (checkedArr: any) => {
    console.log("changeCheckedIds", checkedArr);
    setCheckedIds(checkedArr); //请求用
  };

  useEffect(() => {
   
    //获取默认基金的innerCode
    queryFundBasicInfoList({
      chiname: fundName,
    }).then((res) => {
      console.log(res);
      if (res?.code === "0" && res?.data?.length > 0) {
        setInnerCode(res?.data[0]?.innercode);
      }
    });
    //获取东海基金列表
    queryFundBasicInfoList({}).then((res) => {
      console.log(res);
      if (res?.code === "0" && res?.data?.length > 0) {
        setFundList(res?.data);
      } else {
        setFundList([]);
      }
    });
    //获取数据更新时间
    get_last_job_time().then((res) => {
      if (res?.code === "0") {
        setUpdateTime(res?.data || res?.msg);
      } else {
        setUpdateTime(undefined);
      }
    });
  }, []);

  useEffect(() => {
    if (start && end && innerCode) {
      // 获取折线图数据
      getReportRate({
        // innerCode: "429524",
        // start: "2022-12-01",
        // end: "2022-12-26"
        start: dayjs(start).format("YYYY-MM-DD"),
        end: dayjs(end).format("YYYY-MM-DD"),
        innerCode,
      }).then((res) => {
        setReportLineData(res?.data);
        setIsReportRateReady(true);
      });
    }
  }, [start, end, innerCode]);

  const setWeek = (time) => {
    setEnd(dayjs(time));
    const now = new Date(time);
    const nowTime = now.getTime();
    const day = now.getDay();
    // console.log('day',day)
    let oneDayTime = 24 * 60 * 60 * 1000;
    //显示周一
    const MondayTime = nowTime - (day===0?6:(day - 1)) * oneDayTime;
    setStart(dayjs(MondayTime));
  };

  const setMonth = (time, type) => {
    //type:1是本月 type2非本月
    let date = new Date(time);
    date.setDate(1); // 将当前时间的日期设置成第一天
    setStart(dayjs(date));
    if (type == 1) {
      setEnd(dayjs(time));
      return;
    }
    //非本月

    setEnd(dayjs(new Date(date.getFullYear(), date.getMonth() + 1, 0))); // 这里传入的是字符串
  };

  const setYear = (time) => {
    setEnd(dayjs(time));

    setStart(dayjs(dayjs(time).subtract(1, "year")));
  };

  useEffect(() => {
    if (systemTime && !getUrlParam("start") &&!getUrlParam("end")) {
      setWeek(systemTime);
    }
  }, [systemTime]);

  //
  const onChangeFund = (e, option: any) => {
    console.log("option", option);
    setFundName(option?.children);
    setInnerCode(e);
  };

  //切换统计区间
  const onChangeType = (e) => {
    setType(e);
    if (e == "1") {
      setWeek(systemTime);
    } else if (e == "2") {
      setMonth(systemTime, 1); //设置是否本月
    } else if (e == "3") {
      setYear(systemTime);
    }
  };

  // 保存查询条件
  const handleSaveParams = (e: any, kind: string) => {
    const time = dayjs(e).format("YYYY-MM-DD");
    console.log("time", time, "kind-起始", kind, "type-统计区间", type);
    // let obj = Object.assign({}, searchParams, { [type]: time });
    if (kind === "start" && type == "1") {
      //周
      setWeek(e);
    } else if (kind === "start" && type == "2") {
      //月
      //1是本月 2非本月
      const num =
        dayjs(e).format("YYYY-MM") === dayjs(systemTime).format("YYYY-MM")
          ? 1
          : 2;
      // const num = 2;
      if (num === 1) {
        setMonth(systemTime, num);
      } else {
        setMonth(e, num);
      }
    } else if (type == "3") {
      //年
      if (kind === "start") {
        setStart(dayjs(e));
      } else {
        setEnd(dayjs(e));
      }
    }
  };

  //打印pdf
  const handleDownLoadPdf = () => {
    // setLoading(true);
    const pdfItem = document.getElementById("product_report_pdf_container");
    if (pdfItem) {
      const name = `${fundName}运作${type == "1" ? "周" : type == "2" ? "月" : ""}报${type == "3" ? "表" : ""} ( ${dayjs(start).format( "YYYY-MM-DD")} ~ ${dayjs(end).format("YYYY-MM-DD")} )`;
      Export_Img_Tool(pdfItem, name);

    }
  };

  const handleGotoPdf = () => {
    if (process.env.NODE_ENV === "production") {
      top.window.postMessage(
        {
          url: `/desert-star/product-report?type=img&start=${dayjs(
            start
          ).format("YYYY-MM-DD")}&end=${dayjs(end).format(
            "YYYY-MM-DD"
          )}&innerCode=${innerCode}&fundName=${fundName}&checkType=${type}`,
          // type: "_blank"
        },
        location.origin
      );
    } else {
      window.open(
        `/product-report?type=img&start=${dayjs(start).format(
          "YYYY-MM-DD"
        )}&end=${dayjs(end).format(
          "YYYY-MM-DD"
        )}&innerCode=${innerCode}&fundName=${fundName}&checkType=${type}`
      );
    }
  };

  return (
    <PageWrapper minWidth="1068px" style={{ padding: PDF ? 0 : "16px 16px 32px 16px" }}>
      {!PDF ? (
        <>
          <Title style={{marginLeft: 16}}>产品运作报表</Title>
          <RidingHeader>
            <FlexDiv style={{ marginRight: 24 }}>
              <NewText style={{ marginLeft: 0, marginRight: 8 }}>
                基金产品
              </NewText>
              <SSelect
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={innerCode}
                onChange={onChangeFund}
                // iserror={errorList.includes("lineType")}
                style={{ width: 260 }}
              >
                {fundList?.map((v) => (
                  <Select.Option key={v?.innercode} value={v?.innercode}>
                    {v?.chiname}
                  </Select.Option>
                ))}
              </SSelect>
            </FlexDiv>
            <FlexDiv style={{ marginRight: 8 }}>
              <NewText style={{ marginLeft: 0, marginRight: 8 }}>
                统计区间
              </NewText>
              <SSelect
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={type}
                onChange={onChangeType}
                // iserror={errorList.includes("lineType")}
                style={{ width: 80 }}
              >
                {selectList?.map((v: any) => (
                  <Select.Option key={v?.key} value={v?.key}>
                    {v?.value}
                  </Select.Option>
                ))}
              </SSelect>
            </FlexDiv>
            <CusDatePicker
              label=""
              picker={type == "2" ? "month" : undefined}
              startValue={type == "3" ? dayjs(start) : dayjs(end)}
              endValue={dayjs(end)}
              single={type == "3" ? false : true}
              idName1="riding-date"
              onChange={handleSaveParams}
              // className={styles.customDatePicker}
              disabledDate={ (currentDate: any) => {
                return type=="3"? currentDate && (currentDate >
                      dayjs(end).valueOf()|| currentDate>dayjs(systemTime).valueOf()):
                      currentDate && ( currentDate>dayjs(systemTime).valueOf())
                }
              }
              disabledEndDate={
                 (currentDate: any) => {
                      return  currentDate && (currentDate <
                            dayjs(start).valueOf()|| currentDate>dayjs(systemTime).valueOf())
                        
                    }
              }
              format={type == "2" ? "YYYY/MM" : "YYYY/MM/DD"}
            />
          </RidingHeader>
        </>
      ) : (
        <PdfBtnConttainer
          style={{
            padding:"22px 32px 0 32px"
          }}
        >
          <BorderRedBtn onClick={handleDownLoadPdf} loading={!canDownLoadPdf}>
            <DownImage />
            保存图片
          </BorderRedBtn>
        </PdfBtnConttainer>
      )}
      <div id="product_report_pdf_container">
        <div
          style={PDF?{
            padding:"26px 16px 32px"
          }:undefined}
        >
          <ButtonContainer PDF={PDF}>
            <div>
              <p>
                {fundName}
                <span>
                  {" "}
                  运作{type == "1" ? "周" : type == "2" ? "月" : ""}报
                  {type == "3" ? "表" : ""}
                </span>
              </p>
              <p>
                ｜ {dayjs(start).format("YYYY-MM-DD")} ~{" "}
                {dayjs(end).format("YYYY-MM-DD")}
              </p>
            </div>
            <div>
              {!PDF ? (
                <>
                  {/* <Link to={{ pathname: "/product-report?type=img" }}> */}
                  <BtnTextConttainer>
                    数据同步时间：{updateTime?dayjs(updateTime).format("YYYY-MM-DD HH:MM"): "-"} ｜
                  </BtnTextConttainer>
                  <BorderRedBtn onClick={handleGotoPdf} loading={!innerCode || !start || !end}>
                    <RedDownArrow />
                    导出图片
                  </BorderRedBtn>
                  <BorderRedBtn
                    style={{ marginLeft: 8 }}
                    onClick={onClickExportData}
                    loading={!innerCode || !start || !end}
                  >
                    <RedDownArrow />
                    导出数据
                  </BorderRedBtn>

                  {/* </Link> */}
                </>
              ) : (
                <>
                  <BtnTextConttainer>
                    数据同步时间：{updateTime || "-"} ｜
                  </BtnTextConttainer>
                  <LogoContainer>
                    <img src={icon_logo} />
                  </LogoContainer>
                </>
              )}
            </div>
          </ButtonContainer>
          <LittleTitle title="业绩信息"  mt="24px"/>
          <InfoTable
            innerCode={innerCode}
            start={start}
            end={end}
            type={type}
            onChangeLoading={(loading) => setTableInfoReady(loading)}
            PDF={PDF}
          />
          <TableChart
            start={start}
            end={end}
            innerCode={innerCode}
            checkedkeys={confirmCheckedKeys}
            onChangeLoading={(loading) => setTableChartInfoReady(loading)}
            settingBtn={
              <Popover
                content={
                  <ColumnSelector
                    title="指标自定义"
                    columnOptions={[]}
                    // checkedValues={[]}
                    treeResult={treeResult}
                    checkedKeys={checkedKeys}
                    changeColumns={changeColumns}
                    changeCheckedIds={changeCheckedIds}
                    changeCheckedKeys={changeCheckedKeys}
                    setPopoverVisible={setColumnSetVisible}
                    style={{ height: "108px" }}
                    visible={columnSetVisible}
                    tableId={1}
                    belong="报表"
                    searchTableFieldDTOList={searchTableFieldDTOList}
                  ></ColumnSelector>
                }
                visible={columnSetVisible}
                placement="left"
                onVisibleChange={(visible) => {
                  visible && setColumnSetVisible(visible);
                }}
                overlayClassName={[styles.popoverStyle, styles.bond].join(" ")}
                overlayInnerStyle={{ width: 312, borderRadius: 2 }}
                destroyTooltipOnHide={true}
                arrowPointAtCenter={true}
                trigger="click"
              >
                <Button
                  className={styles.setting_button}
                  icon={
                    <img
                      style={{ opacity: "0.7" }}
                      className="findfit_icon"
                      src={icon_setting}
                    />
                  }
                  onClick={() => {}}
                />
              </Popover>
            }
          />

          <LittleTitle title="成立以来回购利率VS市场利率" />
          <Spin spinning={!isReportRateReady}>
            <LineWrapper PDF={PDF}>
              <ReportLine idName="report-line" lineData={reportLineData} />
            </LineWrapper>
          </Spin>
        </div>
      </div>
    </PageWrapper>
  );
}

export const ButtonContainer = styled.div`
  display: flex;
  border-bottom: 1px solid ${(props) => (props.PDF ? "#4E5257" : "#e4e4e4")};
  margin-top: ${(props) => (props.PDF ? 0 : 62)}px;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 9px;
  > div:nth-child(1) {
    display: flex;
    align-items: center;
  }
  > div:nth-child(1) > p:nth-child(1) {
    font-weight: 600;
    font-size: 24px;
    color: #35425e;
    line-height: 28px;
    margin: 0;
  }
  > div:nth-child(1) > p:nth-child(2) {
    font-weight: 600;
    font-size: 14px;
    color: #35425e;
    line-height: 28px;
    margin: 0 0 0 8px;
  }
  > div:nth-child(1) > p:nth-child(1) > span {
    font-weight: 600;
    font-size: 24px;
    color: #35425e;
    line-height: 28px;
    margin: 0;
  }
  > div:nth-child(2) {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
  }
`;

const LineWrapper = styled.div`
  position: relative;
  padding: 0;
  border: 1px solid ${(props) => (props.PDF ? "#4E5257" : "#e4e4e4")};
  border-radius: 2px;
  text-align: center;
  height: 230px;
  margin-top: 4px;
`;
const PdfBtnConttainer = styled.div`
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  /* padding-right: 32px; */
`;
const BtnTextConttainer = styled.p`
  font-weight: 600;
  font-size: 12px;
  color: rgba(53, 66, 94, 0.7);
  line-height: 28px;
  /* zoom: .83; */
  transform: scale(0.83);
  transform-origin: right center;
  margin-right: 4px;
  margin-bottom: 0;
`;
const LogoContainer = styled.span`
  display: inline-block;
  width: 190px;
  height: 32px;
  img {
    width: 100%;
    height: 100%;
  }
`;
